package com.jgzx.redis.code;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jgzx.redis.config.CacheKeyEnum;
import com.jgzx.redis.config.RedisEnum;
import com.jgzx.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author jackesy
 * @className: CodeTable
 * @description: 字典数据缓存表
 * @create 2021/2/4 17:08
 **/
@Component
public class CodeTable {

    private static CodeTable codeTable;

    @Autowired
    private RedisService redisService;

    @PostConstruct
    public void init() {
        codeTable = this;
        codeTable.redisService = this.redisService;
    }

    /**
     * 根据type获取code列表
     *
     * @param code_type
     * @return
     */
    public static List<CodeVO> getCodeList(String code_type) {
        String cache_key = CacheKeyEnum.SYS_CODE.getValue() + code_type;
        String value = codeTable.redisService.get(RedisEnum.SYS_CODE_CACHE, cache_key);
        if(StrUtil.isEmpty(value)){
            return null;
        }
        return JSON.parseArray(value,CodeVO.class);
    }

    /**
     * 根据key获取code值
     *
     * @param code_type
     * @param code_key
     * @return
     */
    public static String getValue(String code_type, String code_key) {
        List<CodeVO> codeList = getCodeList(code_type);
        if (CollUtil.isNotEmpty(codeList)) {
            for (CodeVO codeVO : codeList) {
                if (code_key.equals(codeVO.getCode_key())) {
                    return codeVO.getCode_value();
                }
            }
        }
        return "";
    }

    /**
     * 根据key获取code名称
     *
     * @param code_type
     * @param code_key
     * @return
     */
    public static String getName(String code_type, String code_key) {
        List<CodeVO> codeList = getCodeList(code_type);
        if (CollectionUtil.isNotEmpty(codeList)) {
            for (CodeVO codeVO : codeList) {
                if (code_key.equals(codeVO.getCode_key())) {
                    return codeVO.getCode_name();
                }
            }
        }
        return "";
    }
}
